//
//  CoreDataManager.m
//  ConghuiEducation
//
//  Created by leo on 16/9/1.
//  Copyright © 2016年 sample. All rights reserved.
//

#import "CoreDataManager.h"
#import "AppDelegate.h"


static CoreDataManager* _sharedManager = nil;

@implementation CoreDataManager{
    AppDelegate* appDelegate;
    NSManagedObjectContext* appContext;
}


+ (CoreDataManager*)sharedManager{
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        _sharedManager = [[self alloc] init];
    });
    return _sharedManager;
}
- (id)init{
    self = [super init];
    appDelegate = [AppDelegate sharedApplicationDelegate];
    appContext = [appDelegate managedObjectContext];
    return self;
}

- (void)save{
    [appDelegate saveContext];
}

- (void)deleteEntity:(NSManagedObject*)obj{
    [appContext deleteObject:obj];
    [self save];
}

- (NSArray *)getAllPupils{
    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Pupil" inManagedObjectContext:appContext];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDescription];
    
    NSPredicate *filter = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"pupil_id != '0'"]];
    [request setPredicate:filter];
    
    NSError *error = nil;
    NSArray *arrRecords = [appContext executeFetchRequest:request error:&error];
    if (error!=nil) {
        NSLog(@"%@",error);
    }else{
        return arrRecords;
    }
    return nil;
}

- (NSInteger)getNewPupilID{
    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Pupil" inManagedObjectContext:appContext];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDescription];
    
    NSPredicate *filter = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"pupil_id != '0'"]];
    [request setPredicate:filter];
    
    NSError *error = nil;
    NSArray *arrRecords = [appContext executeFetchRequest:request error:&error];
    if (error!=nil) {
        NSLog(@"%@",error);
    }else{
        //NSLog(@"找到了：%@",arrRecords);
        NSArray *sortedArray = [arrRecords sortedArrayUsingComparator:^NSComparisonResult(id obj1,id obj2){
            Pupil *pupil1 = (Pupil *)obj1;
            Pupil *pupil2 = (Pupil *)obj2;
            if([pupil1.pupil_id integerValue]>[pupil2.pupil_id integerValue]){
                return -1;
            }
            return 1;
        }];
        return [[[sortedArray firstObject] pupil_id] integerValue]+1;
        //NSLog(@"sortedArray:%@",sortedArray);
    }
    
    return 1;
}

- (void)savePupilsList{
    for(int i=0;i<30;++i){
        Pupil* pupil = [NSEntityDescription insertNewObjectForEntityForName:@"Pupil" inManagedObjectContext:appContext];
        [pupil setPupil_id:[NSNumber numberWithInteger:i+1]];
        [pupil setName:@"张文学"];
        [self save];
    }
}

- (void)saveNewPupilWithDic:(NSDictionary *)dic{
    Pupil* pupil = [NSEntityDescription insertNewObjectForEntityForName:@"Pupil" inManagedObjectContext:appContext];
    [pupil setPupil_id:[dic objectForKey:@"pupil_id"]];
    [pupil setName:[dic objectForKey:@"name"]];
    [pupil setAddress:[dic objectForKey:@"address"]];
    [pupil setFather_name:[dic objectForKey:@"father_name"]];
    [pupil setPhone_number:[dic objectForKey:@"phone_number"]];
    [pupil setGrade_number:[dic objectForKey:@"grade"]];
    [pupil setClass_number:[dic objectForKey:@"class"]];
    [self save];
}

//- (void)findOneRecordWith:(NSDictionary *)recordDic{
//    //从coreData取一个数据，如果不存在则存储进去
//    NSInteger book_id = [NSNumber getObjectIntValue:[recordDic objectForKey:@"book_id"]];
//    NSString *clickKey = [recordDic objectForKey:@"clickKey"];
//    NSInteger count = [NSNumber getObjectIntValue:[recordDic objectForKey:@"count"]];
//    NSString *date = [recordDic objectForKey:@"date"];
//    NSInteger timevalue = [NSNumber getObjectIntValue:[recordDic objectForKey:@"timevalue"]];
//    
//    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"ReadRecord" inManagedObjectContext:appContext];
//    NSFetchRequest *request = [[NSFetchRequest alloc] init];
//    [request setEntity:entityDescription];
//    
//    NSPredicate *filter = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"book_id='%ld' AND date='%@'",book_id,date]];
//    [request setPredicate:filter];
//    
//    NSError *error = nil;
//    NSArray *arrRecords = [appContext executeFetchRequest:request error:&error];
//    if (error!=nil) {
//        NSLog(@"%@",error);
//    }
//    else{
//        ReadAnalysisConfig *config = [AppDelegate readAnalysisConfig];
//        if([arrRecords count] > 0){
//            for (ReadRecord* record in arrRecords) {
//                NSDictionary *click_history = record.click_history;
//                //此处从服务器获取配置参数 index<1 content<1 chapter < 1
//                NSInteger clickMaxCount = 0;
//                if([clickKey isEqualToString:@"index"]){
//                    //首页
//                    clickMaxCount = config.home_page;
//                }else if([clickKey isEqualToString:@"content"]){
//                    //目录
//                    clickMaxCount = config.catalog;
//                }else{
//                    //章节
//                    clickMaxCount = config.word_read_count>0?count:1;
//                }
//                if([[click_history objectForKey:clickKey] integerValue] < clickMaxCount && [record.allcount integerValue] < config.max_readcount_per_device_perbook){
//                    //没有累加过，需要累加
//                    record.count = [NSNumber numberWithInteger:count+[NSNumber getObjectIntValue:record.count]];
//                    record.timevalue = [NSNumber numberWithInteger:timevalue];
//                    record.allcount = [NSNumber numberWithInteger:count+[NSNumber getObjectIntValue:record.allcount]];
//                    NSMutableDictionary *dic = [record.click_history mutableCopy];
//                    [dic setObject:record.count forKey:clickKey];
//                    record.click_history = dic;
//                    NSLog(@"阅读过这本书，更新点击数%@ %@ %@ %@ %@",record.book_id,record.date,record.timevalue,record.count,record.click_history);
//                }
//            }
//            [self save];
//        }else{
//            //保存进去吧
//            //NSLog(@"第一次阅读，直接保存book_id=%ld",book_id);
//            ReadRecord* record = [NSEntityDescription insertNewObjectForEntityForName:@"ReadRecord" inManagedObjectContext:appContext];
//            record.book_id = [NSNumber numberWithInteger:book_id];
//            record.date = date;
//            record.timevalue = [NSNumber numberWithInteger:timevalue];
//            record.count = [NSNumber numberWithInteger:count];
//            record.allcount = [NSNumber numberWithInteger:count];
//            record.click_history = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInteger:count],clickKey, nil];
//            [self save];
//        }
//    }
//}


//- (NSMutableDictionary *)findRecordListWithDate:(NSString *)date{
//    //根据阅读日期，选择数据
//    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"ReadRecord" inManagedObjectContext:appContext];
//    NSFetchRequest *request = [[NSFetchRequest alloc] init];
//    [request setEntity:entityDescription];
//    
//    NSPredicate *filter = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"date = '%@' AND count > 0",date]];
//    [request setPredicate:filter];
//    
//    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
//    NSError *error = nil;
//    NSArray *arrRecords = [appContext executeFetchRequest:request error:&error];
//    if (error!=nil) {
//        NSLog(@"%@",error);
//    }else{
//        if([arrRecords count] > 0){
//            for (ReadRecord* record in arrRecords){
//                //NSLog(@"需要上传的数据：%@ %@ %@ %@",record.book_id,record.date,record.timevalue,record.count);
//                [dic setObject:[NSDictionary dictionaryWithObjectsAndKeys:record.book_id,@"book_id",record.count,@"count",record.timevalue,@"timevalue",record.date,@"date", nil] forKey:record.book_id];
//            }
//        }
//    }
//    return dic;
//}

@end
